import easyquotation
import baostock as bs

from util.daylink import daylink
from scipy.signal import find_peaks
import numpy as np
import pandas as pd
from scipy import signal   #滤波等
import matplotlib.pyplot as plt


classnum=0

def getNext(stockdata,len,typeNum, lenNum,nextNum,res,datalist):
    classnum=lenNum
    data = stockdata.iloc[lenNum]
    val = data['val']
    #初始
    if res ==None and lenNum < len:
        res =val
    #超过长度，则返回
    if lenNum >= len:
        return  res
    if nextNum >= len:
        return  res
    data1 = stockdata.iloc[nextNum]
    type = data1['type']
    #不一致，说明高低点变换，返回
    if type != typeNum :
       return  res
    if type == typeNum :
        nextNum = nextNum + 1
        lenNum = lenNum+1
        val1 = data1['val']
        if type == 2 :
            if val >=  val1 :
                #该条数据被剔除
                time = data['time']
                t = data['type']
                dd=time+str(t)
                #data = data.copy()
                datalist.append(dd)
                #data['st']=2
                return  getNext(stockdata,len, typeNum, lenNum, nextNum,val1,datalist)
            elif val <  val1:

                time = data1['time']
                t = data1['type']
                dd = time +str(t)
                datalist.append(dd)
                return  getNext(stockdata,len, typeNum, lenNum, nextNum,val1,datalist)
        if type == 1 :
            if val <=  val1 :
                #该条数据被剔除
                time = data['time']
                t = data['type']
                dd = time +str(t)
                # data = data.copy()
                datalist.append(dd)
                return  getNext(stockdata,len, typeNum, lenNum, nextNum,val1,datalist)
            elif val >  val1:
                time = data1['time']
                t = data1['type']
                dd = time + str(t)
                datalist.append(dd)

                return  getNext(stockdata,len, typeNum, lenNum, nextNum,val1,datalist)
    return  res


lg = bs.login(user_id='anonymous', password='123456')
fromdate = daylink().get_day_of_day(-100)
todate = daylink().get_day_of_day(0)
#lg = bs.login(user_id='anonymous', password='123456') ,tradestatus
field = 'date, code, open, high, low, close,tradestatus'
rs = bs.query_history_k_data_plus('sh.600406',
                                              field,
                                              # "date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,peTTM,pbMRQ,psTTM,pcfNcfTTM,isST",
                                              start_date='%s-%s-%s' % (
                    fromdate.year, fromdate.month, fromdate.day), end_date='%s-%s-%s' % (
                    todate.year, todate.month, todate.day),
                                              frequency='d',
                                              adjustflag="2")

result_list = []
#print(rs.get_row_data())
while (rs.error_code == '0') & rs.next():

    d = rs.get_row_data()
    result_list.append(d)

df_init = pd.DataFrame(result_list, columns=rs.fields)
#print(df_init)


df_init = df_init.astype({'high': 'float', 'open': 'float', 'close': 'float', 'low': 'float'})
#df_init.date = pd.to_datetime(df_init.date)
print(df_init)
value_list = df_init.high.tolist()
value_list = np.array(value_list)
time_list = df_init.date.tolist()
time_list=np.array(time_list)

indices = find_peaks(value_list, height=None, threshold=None, distance=None,
                             prominence=None, width=None, wlen=None, rel_height=None,
                             plateau_size=None)
stockdata = pd.DataFrame(columns=['val', 'ind', 'type','time','st'])
#print(indices)

val = value_list[indices[0]]
ind = indices[0]
plt.figure(figsize=(6, 4))
plt.plot(np.arange(len(value_list)), value_list)
plt.plot(indices[0], value_list[indices[0]], 'o')
for i in range(0, len(ind)):
       stockdata = stockdata.append({'val': val[i], 'ind': ind[i], 'type': 1,'time':time_list[ind[i]],'st':1}, ignore_index=True)


value_list =df_init.low.tolist()
value_list = np.array(value_list)
#print(value_list)
value_list = value_list*-1
indices = find_peaks(value_list, height=None, threshold=None, distance=None,
                             prominence=None, width=None, wlen=None, rel_height=None,
                             plateau_size=None)
#stockdata = pd.DataFrame(columns=['val', 'ind', 'type'])
val = value_list[indices[0]]
ind = indices[0]
value_l = value_list * -1

plt.plot(np.arange(len(value_list)), value_list*-1)
plt.plot(indices[0], value_l[indices[0]], 'o')
plt.show()
resesesdata = pd.DataFrame(columns=['val', 'type'])
for i in range(0, len(ind)):
    stockdata = stockdata.append({'val': val[i]*-1, 'ind': ind[i], 'type': 2,'time':time_list[ind[i]],'st':1}, ignore_index=True)
stockdata = stockdata.sort_values(by=['ind'], ascending=True)
print(stockdata)
len = len(stockdata)

datalist =[]
num =0
for i in range(len):

    #print('22222222222',datalist)

    #print(i)
    data = stockdata.iloc[i]
    type = data['type']
    st = data['st']
    time =  data['time']
    dd = time+str(type)



    #低
    if i<len-1  and  dd  not in datalist:
       #print(time)
       if type == 2 :

           d = getNext(stockdata, len, 1, i+1, i+2, None,datalist)
           if d!= None:
               rdata = round(((d - data['val']) / data['val']) * 100, 2)
               print('上升:', rdata)

       if type == 1:
           d = getNext(stockdata, len, 2, i + 1, i + 2, None,datalist)
           if  d!= None:
               rdata = round(((data['val'] - d) / data['val']) * 100, 2)
               print('下降:', rdata*-1)

































































































































































































































































